#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>  
#include <ctype.h> 
#include <fcntl.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>

#if defined(LINUX)
#include <unistd.h>  
#include <sys/time.h>
#include <pthread.h>
#include <dirent.h>  
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/reboot.h>
#include <linux/rtnetlink.h>
#include <sys/wait.h>  
#else
#include <io.h>
#include <direct.h>
#include <Iphlpapi.h>
#pragma comment(lib,"iphlpapi.lib") 
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
#define snprintf _snprintf
#endif

#include "Logging.h"
#include "ConfigFile.h"
#include "ArrayList.h"
#include "TcpServerClient.h"
#include "cpool.h"
#include "SqlAccess.h"
#include "GpsDataStruct.h"

void     when_sigint();
void     when_sigkill();
void     ProgramEnd();

void *thread_function(void *arg);
void *thread_add(void *arg);
GpsDataStruct* s;
SQL_CONN_POOL * sp;

int main(int argc, char **argv)
{
	/* whp test */
	 
	
	//printf("--%d-- \n", node->index);
	//printf("busy--%d--\n", sp->busy_number);
	//char t1[50] = {"gpsdata"};
	//char t2[500] = {"clientId, matchId, time, latitude, latitudeHemisphere, longitude, longitudeHemisphere, speed, course, mileage"};
	//char t3[500] = {"'1','1','2000-11-11 11:11:11','2','N','2','E','10','10','10'"};
/*
	char         cName[300] = { "1" };
	char         cTime[50] = { "2019-01-01 01:01:01" };
	char         cLatitude[50] = { "20" };
	char         cLatitudeH[10] = { 'N' };
	char         cLongitude[50] = { "30" };
	char         cLongitudeH[10] = { 'E' };
	char         cSpeed[50] = { "30" };
	char         cCourse[50] = { "20" };
	char         cMileage[50] = { "50" };

	s = (GpsDataStruct*)malloc(sizeof(GpsDataStruct));
	sprintf(s->czName, "%s", cName);
	sprintf(s->czTime, "%s", cTime);
	sprintf(s->czLatitude, "%s", cLatitude);
	sprintf(s->czLatitudeH, "%s", cLatitudeH);
	sprintf(s->czLongitude, "%s", cLongitude);
	sprintf(s->czLongitudeH, "%s", cLongitudeH);
	sprintf(s->czSpeed, "%s", cSpeed);
	sprintf(s->czCourse, "%s", cCourse);
	sprintf(s->czMileage, "%s", cMileage);
*/

	//if (mysql_query(&(node->fd), "insert into gpsdata (clientId, matchId, time, latitude, latitudeHemisphere, longitude, longitudeHemisphere, speed, course, mileage) values ('1','1','2000-11-11 11:11:11','2','N','2','E','10','10','10')"))
	//if(insertInto(&(node->fd),t1,t2,t3))
	//if(insertGpsDataStruct(&(node->fd),s))
	//{                                                    
	//	printf("query error.\n");                                     
	//	return -1;                                      
	//}
	//else  
	//	printf("succeed!!!!!\n");  

	//changeNodeNum(sp, 0);//减少
	//changeNodeNum(sp, 1);//增加
	//sql_pool_destroy(sp);

    	/* end test */

	/* test queue */

	InitQueue();

/*
	int n = 0;
	while(n<10)
	{
	char         tName[300] = { "1" };
	char         tTime[50] = { "2019-01-01 01:01:01" };
	char         tLatitude[50] = { "20" };
	char         tLatitudeH[10] = { 'N' };
	char         tLongitude[50] = { "30" };
	char         tLongitudeH[10] = { 'E' };
	char         tSpeed[50] = { "30" };
	char         tCourse[50] = { "20" };
	char         tMileage[50] = { "50" };
	GpsDataStruct* tp = (GpsDataStruct*)malloc(sizeof(GpsDataStruct));
	sprintf(tp->czName, "%s", tName);
	sprintf(tp->czTime, "%s", tTime);
	sprintf(tp->czLatitude, "%s", tLatitude);
	sprintf(tp->czLatitudeH, "%s", tLatitudeH);
	sprintf(tp->czLongitude, "%s", tLongitude);
	sprintf(tp->czLongitudeH, "%s", tLongitudeH);
	sprintf(tp->czSpeed, "%s", tSpeed);
	sprintf(tp->czCourse, "%s", tCourse);
	sprintf(tp->czMileage, "%s", tMileage);
	if(PushGpsData(tp))
	{
		printf("添加失败！！！！！！！！！！！！！！\n");
	}
	n++;
	}
*/	

	/* end test */

	SetVersion("1.01");

	if( InitLogging(1, &ReadConfigFile) < 0 )
	{
        WriteFileLog(LFATAL,"初始化日志模块错误，程序退出！");
	    exit(0);
	}
    WriteFileLog(LHINT,"");
    WriteFileLog(LHINT,"---------- Gps定位数据中转服务%s版本已经开启 ---------",GetAppVersion());
    WriteFileLog(LHINT,"");
    WriteFileLog(LHINT,"");

    sp = sql_pool_create(10, dbServer, dbPort, dbName, dbUser, dbPass); 

/*
    SQL_NODE *node  = get_db_connect(sp);  

	if (NULL == node)  
	{  
		printf("get sql pool node error.\n"); 
	} 
    char clientname[50] = {"test"};
    int tmpget;
    tmpget = GetIdWithClientName(&(node->fd),clientname);
    printf("%d\n",tmpget);
*/
	pthread_t a_thread;
	pthread_t  add_thread;
   	void *thread_result;
	void *thread_result2;
	int res = 0;
    	res = pthread_create(&a_thread, NULL, thread_function, NULL);
   	 if (res != 0)
   	 {
      	  	//perror("Thread creation failed!");
      	  	//exit(EXIT_FAILURE);
		printf("error !!!!!!!!!!!!\n");
   	 }
	//res = pthread_create(&add_thread, NULL, thread_add, NULL);
   	 //if (res != 0)
   	 //{
      	  	//perror("Thread creation failed!");
      	  	//exit(EXIT_FAILURE);
	//	printf("error !!!!!!!!!!!!\n");
   	 //}

    ProgramStartsRecording();

	SetSaveDirectory();

    SetVersion("1.01");

    ArrayListInit(&al,1000);
	//NameListInit(&n1, 200);

    if( StartTcpServer("GpsContact", tcpServerPort, &TcpSocketInterface) < 0 )
	{
		WriteFileLog(LERROR,"开启TCP服务程序失败，程序退出！");
		exit(0);
	}

    for(;;)
    {
        signal(SIGINT,when_sigint);  //当接收到SIGINT信号时，调用when_sigint函数
        signal(SIGTERM,when_sigkill);  //当接收到SIGTERM信号时，调用when_sigkill函数
        usleep(1);
    }

    ArrayListDestroy(&al);
    DestroyLogging();
    return(0);
}

void when_sigint()
{
	WriteFileLog(LHINT,"已经接收到了SIGINT信号，程序将退出！");

	StopTcpServer();

    ArrayListDestroy(&al);
    DestroyLogging();
    exit(0);
}

void when_sigkill()
{
	WriteFileLog(LHINT,"已经接收到了SIGTERM信号，程序将退出！");

	StopTcpServer();

    ArrayListDestroy(&al);
    DestroyLogging();
    exit(0);
}

void ProgramEnd()
{
	StopTcpServer();
    ArrayListDestroy(&al);
    DestroyLogging();
    exit(0);
}

//单独写struct
/*void *thread_function(void *arg)
{
    //sleep(1);
    while(1)
    {
	sleep(1);
	GpsDataStruct* tmp = PopGpsData();
	if(NULL == tmp)
		continue;
	SQL_NODE *node  = get_db_connect(sp);  

	if (NULL == node)  
	{  
		printf("get sql pool node error.\n"); 
		free(tmp);
		return -1;  
	} 
	
	if(insertGpsDataStruct(&(node->fd),tmp))
	{                                                    
		printf("query error.\n");   
                release_node(sp,node);     
		free(tmp);        
		return -1;                                      
	}
	else  
		WriteFileLog(LHINT, "succeed!!!!!"); 
	release_node(sp,node);
	free(tmp);
    }
}*/

//写struct group
void *thread_function(void *arg)
{
    //获取比赛ID
    /*int matchid = -1;
    SQL_NODE *mynode  = get_db_connect(sp);
    if(NULL == mynode)
    {
	WriteFileLog(LERROR, "获取比赛id时，没有取到数据库连接！");
	ProgramEnd();
    }
    matchid = GetIdWithMatchName(&(mynode->fd), matchName);
    if(-1 == matchid)
    {
	WriteFileLog(LERROR, "获取比赛id时，没有取得可用id！");
	ProgramEnd();
    }
    matchId = matchid;
    release_node(sp,mynode);*/

    //sleep(2);
    while(1)
    {
	//sleep(1);
	usleep(recSec);
	GpsDataStruct** tmp = NULL;
	int i = 0;
	int lens = GetAllFromGpsdataQ(&tmp);
	if(lens>120)
	{
		printf("lens is too long %d\n",lens);
		for(i;i<lens;i++)
			free(tmp[i]);
		free(tmp);
		continue;
	}	
	if(lens<=0 || NULL == tmp)
	{
		//printf("tmp is null\n");
		continue;
	}
	SQL_NODE *node  = get_db_connect(sp);  

	if (NULL == node)  
	{  
		printf("get sql pool node error.\n"); 
		for(i;i<lens;i++)
			free(tmp[i]);
		free(tmp);
		continue;  
	} 
	int ret;
	ret = insertGpsDataGroup(&(node->fd),tmp,lens);
	if(-1==ret)
	{                                                    
		printf("insert error param is null.\n");   
                release_node(sp,node);     
		for(i;i<lens;i++)
			free(tmp[i]);
		free(tmp);
		continue;                                      
	}
	else if(ret<-1)
	{
		printf("insert error.\n");   
		free(tmp);
             release_node(sp,node);     
		continue;  
	}
	else  
	{
		free(tmp);
		WriteFileLog(LHINT, "succeed!!?!!"); 
	}
	release_node(sp,node);
    }
}


void *thread_add(void *arg)
{
    while(1)
    {
	//sleep(1);
	usleep(10000);
	char         tName[300] = { "test2" };
	char         tTime[50] = { "2019-01-01 01:01:01" };
	char         tLatitude[50] = { "20" };
	char         tLatitudeH[10] = { 'N' };
	char         tLongitude[50] = { "30" };
	char         tLongitudeH[10] = { 'E' };
	char         tSpeed[50] = { "30" };
	char         tCourse[50] = { "20" };
	char         tMileage[50] = { "50" };
	GpsDataStruct* tp = (GpsDataStruct*)malloc(sizeof(GpsDataStruct));
	sprintf(tp->czName, "%s", tName);
	sprintf(tp->czTime, "%s", tTime);
	sprintf(tp->czLatitude, "%s", tLatitude);
	sprintf(tp->czLatitudeH, "%s", tLatitudeH);
	sprintf(tp->czLongitude, "%s", tLongitude);
	sprintf(tp->czLongitudeH, "%s", tLongitudeH);
	sprintf(tp->czSpeed, "%s", tSpeed);
	sprintf(tp->czCourse, "%s", tCourse);
	sprintf(tp->czMileage, "%s", tMileage);
	if(PushGpsData(tp))
	{
		printf("添加失败！！！！！！！！！！！！！！\n");
	}
    }
}



